﻿ValueListManager = {
  service: "ValueListService.svc/ValueList",
  
  tabs: null,
  list: {},
  data: null,
  valueid: null,
  newval: null,
  newuri: null,

  log: function (msg) {
    if (console) {
      console.log(msg);
    }
  },

  initialize: function () {
    this.tabs = $("#tabs").tabs();
    this.autoCompleteCache = {};
    this.uris = [];
    this.getList();

    $("#uritext").hide();

    ValueListManager.addHide();
    ValueListManager.modHide();

    $("#addButton").button().click(function () {
      ValueListManager.addValueList();
      ValueListManager.addHide(); 
    });

    // Capture the Enter key when creating values
    $.each([ "texturi", "cstruc", "desc" ], function( i, val ){
      $( "#" + val ).keydown( function( event ){
        if( event.which == 13 ){
          $("#addButton").click();
        }
      })
    });

    $("#modifyValueButton").button().click(function () {
      ValueListManager.modifyValueList();
    });

    // Capture the Enter key when editing values
    $.each([ "moduri", "modcstruc", "moddesc" ], function( i, val ){
      $( "#" + val ).keydown( function( event ){
        if( event.which == 13 ){
          $("#modifyValueButton").click();
        }
      })
    });

    $("#deleteValueButton").button().click(function () {
      ValueListManager.deleteValueList();
       $("#dialog").dialog("close");
       ValueListManager.modHide();
    });

    var that = this;
    // Enable autocomplete for the ValueList Value
    $("#textvalue").autocomplete({
      minLength: 0,
      source: function( request, response ){
        var term = request.term.toLowerCase();
        var result = [];
        var uri = $("#adduri").val();

        if( uri in that.autoCompleteCache ){
          var cachedItems = that.autoCompleteCache[uri];
          console.log( cachedItems );
          for( var i = 0; i < cachedItems.length; i++  ){
            var item = cachedItems[i].toLowerCase();
            if( item.indexOf( term ) > -1 ){
              result.push( cachedItems[i] );
            }
          }
        }

        result.sort();
        response( result );
      }
    });

  $("#modvalue").autocomplete({
    minLength: 0,
    source: function( request, response ){
      var term = request.term.toLowerCase();
      var result = [];
      var uri = $("#moduri").val();

      if( uri in that.autoCompleteCache ){
        var cachedItems = that.autoCompleteCache[uri];
        console.log( cachedItems );
        for( var i = 0; i < cachedItems.length; i++  ){
          var item = cachedItems[i].toLowerCase();
          if( item.indexOf( term ) > -1 ){
            result.push( cachedItems[i] );
          }
        }
      }

      result.sort();
      response( result );
    }
  });

  },

  addHide: function () {
    $("#dialog").hide();
  },

  modHide: function () {
    $("#error").hide();
    $("#modtextfac").hide();
    $("#modtextics").hide();
    $("#modtextunits").hide();
    $("#modtextresp").hide();
    $("#modtextobs").hide();
    $("#modifyuri").hide();
  },

  getList: function () {
    $.ajaxSetup({ cache: false });
    $.ajax({ url: this.service, context: this, success: this.loadList});
  },

  // Adds an item to the cache for Value autocomplete
  addToAutoCompleteCache: function( item ){
    if( !(item.uri in this.autoCompleteCache) ){
      this.autoCompleteCache[item.uri] = [];
    }

    if( item.value && item.value != "undefined" ){
      this.autoCompleteCache[item.uri].push( item.value );
    }
  },

  // Adds a URI to the local cache
  addUri: function( uri ){
    if( uri && uri != "undefined" && $.inArray( uri, this.uris ) < 0 ){
      this.uris.push( uri );
    }
  },

  loadList: function(data, code, xhr) {
    this.list = {};
    this.autoCompleteCache = {};
    this.data = data;
    this.uris = [];

    try {
      var valListElts = data.documentElement.getElementsByTagName("valList");
      
      for(var i = 0; i<valListElts.length;i++)
      {
        var urnElt = valListElts[i].getElementsByTagName("valueListUrn")[0];
        var valueElts = valListElts[i].getElementsByTagName("string");

        for (var j = 0; j < valueElts.length; j++) {
          var l;
          if ($.browser.msie) {
            l = {
              id: urnElt.text + "::" + valueElts[j].text,
              uri: urnElt.text,
              value: valueElts[j].text
            };
          } else {
            l = {
              id: urnElt.textContent + "::" + valueElts[j].textContent,
              uri: urnElt.textContent,
              value: valueElts[j].textContent
            };
          }
          this.list[l.id] = l;
          this.addToAutoCompleteCache(l);
          this.addUri(l.uri);
        }
      }
    }
    catch (e) {
      if (console) {
        console.log("loadList error: " + e);
      }
    }

    ValueListManager.updateList();
  },

  addtab: function(){
      $("#tabs-2").click(function(event){
    //alert("add tab");
    })
  },

  updateList: function () {
     $('#vltable').html("");
    var html = $('#vltable').html();
    html = "<tr><th>ValueList</th><th>URI</th><th>Value</th><th>Command Structure</th><th>Description</th></tr>";
    var ct = 0;
    for(var l in this.list) {
      ct = ct + 1;
      var li = this.list[l];
      html = html + "<tr id='" + li.id + "'><td>" + ct + "</td><td>" + li.uri + "</td><td>" + li.value + "</td><td>" + li.cstruc + "</td><td>" + li.desc + "</td></tr>";
    }
    if(ct < 1) {
      html = "No Rules In Database.<br />Click Here to Add One.";
    }
    $('#vltable').html(html);

    // Add all the URIs to the #adduri dropdown
    $.each( this.uris, function( i, value ){
      $("#adduri").append( $("<option></option>").text( value ) );
    });

    $(".striped tr").mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
    $(".striped tr:even").addClass("alt");

    // Only allow a custom URI if "Other" is selected
    $("#adduri").change(function(event) {
      var isCustomUri = $(this).val() == "Other";
      $("#uritext").toggle( isCustomUri );
    });

    $("#keywordadd").change(function(event) {
      
      if($("#keywordadd").val()== "EDXL"){
        var select = document.getElementById("addedxl");
        select.style.display= "block";

        var mexlselect = document.getElementById("addmexl");
        mexlselect.style.display = "none";

        var mexltext = document.getElementById("addmexltext");
        mexltext.style.display = "none";
        }
        else if($("#keywordadd").val() == "MEXL"){
        var mexlselect = document.getElementById("addmexl");
        mexlselect.style.display = "block";

        var select = document.getElementById("addedxl");
        select.style.display= "none";

        var text = document.getElementById("addedxltext");
        text.style.display = "none";
      }
      else{
        var select = document.getElementById("addedxl");

        var mexlselect = document.getElementById("addmexl");
        
        select.style.display= "none";

        mexlselect.style.display = "none";
      }
    });

      $("#addedxl").change(function(event) {
      
      if($("#edxladd").val()== "Other"){
      var text = document.getElementById("addedxltext");
      text.style.display= "block";

      var mexltext = document.getElementById("addmexltext");
      mexltext.style.display = "none";
      }
      else{
      var text = document.getElementById("addedxltext");
      text.style.display = "none";

      var mexltext = document.getElementById("addmexltext");
      mexltext.style.display = "none";
      }
      });

      $("#addmexl").change(function(event) {
      
      if($("#mexladd").val()== "Other"){
      var text = document.getElementById("addmexltext");
      text.style.display= "block";

      var edxltext = document.getElementById("addedxltext");
      edxltext.style.display = "none";
      }
      else{
      var text = document.getElementById("addmexltext");
      text.style.display = "none";

      var edxltext = document.getElementById("addedxltext");
      edxltext.style.display = "none";
      }
      });

    $("#vltable tr").click(function(event) {
       var index = $('#vltable tr').index(this); 
//       alert('You Clicked row ' + index);

       for(index in this.list){
       var selected= this.list[index];
       }

      var $td= $(this).closest('tr').children('td');  
  
      valueid= $(this).closest('tr').attr('id');

//      alert("This is the id " + valueid);
             
      newuri= $td.eq(1).text();
      newval= $td.eq(2).text();
      var newcstruc= $td.eq(3).text();
      var newdesc= $td.eq(4).text(); 
     

      $("#moduri").val(newuri);
      $("#modvalue").val(newval);
      $("#modcstruc").val(newcstruc);
      $("#moddesc").val(newdesc);
      $( "#dialog" ).dialog({
        height: 500,
        width: 500,
        modal: true
      });
     
    });
  },

  // Checks the URI, value, command structure, and description for valid input
  // Returns a string with errors, which is empty if the input is valid.
  validate: function( uri, value, cstruc, desc ){
    
    var error = "";

    if( !uri || uri == "" || uri == "Default" ) {
        error += "Value List URI cannot be blank<br />";
    }

    if( !value || value == "") {
        error += "Value cannot be blank<br />";
    }

    return error;
  },
   
  addValueList: function(rule) {

    var uri;
    if( $("#adduri").val() == "Other" ){
      uri = $("#texturi").val();
    } else {
      uri = $("#adduri").val();
    }

    var value= $("#textvalue").val();
    var cstruc = $("#cstruc").val();
    var desc = $("#desc").val();

    $("#error").slideUp();
    var error = this.validate( uri, value, cstruc, desc );

    if( error ) {
      $('#error').html(error).slideDown();
      return;
    }

    $("#uritext").hide();

    var xml = "<?xml version='1.0'?><ValueList><VLKey /><ValueListURI>" + uri + "</ValueListURI><Value>" + value + "</Value><CommandStructure>" + cstruc + "</CommandStructure>" + "<Description>" + desc + "</Description></ValueList>";

    $.ajax({
      url: this.service, 
      context: this, 
      type: 'POST',
      data: xml,
      processData: false,
      contentType: 'text/xml',
      success: this.addSuccess,
      error: this.addFail
    });
  },

  modifyValueList: function(rule) {
    $("#modify").slideUp();

    var uri = $("#moduri").val();
    var value = $("#modvalue").val();
    var cstruc = $("#modcstruc").val();
    var desc = $("#moddesc").val();

    debugger
    var error = this.validate( uri, value, cstruc, desc );    
    if( error ) {
      $('#modify').html(error).slideDown();
      return;
    }

    var xml = "<?xml version='1.0'?><ValueList><VLKey /><ValueListURI>" + uri + "</ValueListURI><Value>" + value +
      "</Value><CommandStructure>" + cstruc + "</CommandStructure>" + 
      "<Description>" + desc + "</Description></ValueList>";

    $.ajax({
      url: this.service + "/" + valueid, 
      context: this, 
      type: 'POST',
      data: xml,
      processData: false,
      contentType: 'text/xml',
      success: this.modSuccess,
      error: this.addFail
    });
    
  },

  addSuccess: function(data, code, xhr) {
  //alert("entered add success");
    $(':input', '#tabs-2')
    .not(':button, :submit, :reset, :hidden')
    .val('')
    .removeAttr('checked')
    .removeAttr('selected');

    ValueListManager.getList();
    $(ValueListManager.tabs).tabs('select', 0);
  },

  modSuccess: function(data, code, xhr) {
 // alert("entered mod success");
    $(':input', '#dialog')
    .not(':button, :submit, :reset, :hidden')
    .val('')
    .removeAttr('checked')
    .removeAttr('selected');

   $("#dialog").dialog("close");
   ValueListManager.modHide();

    ValueListManager.getList();
    $(ValueListManager.tabs).tabs('select', 0);

  },

  addFail: function() {
    alert("Adding rule failed. Server error.");
  },

 deleteSuccess: function(){

    $(':input','#modifiedvlform')
     .not(':button, :submit, :reset, :hidden')
     .val('')
     .removeAttr('checked')
     .removeAttr('selected');

     ValueListManager.getList();
    $(ValueListManager.tabs).tabs('select', 0);

  },

  deleteFail: function() {
    alert("Deleting rule failed. Server error.");
  },

 deleteValueList: function(data) {

      $.ajax({ url: this.service + "/" + valueid, 
             context: this, 
             type: 'DELETE',
             data: data,
             processData: false,
             contentType: 'text/xml',
             success: this.deleteSuccess,
             error: this.deleteFail});
   
    alert("Deleted");
  }
}
